<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="客户画像" data-page-identification="p_ydkimisyyq">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_nmqzkbwwu1 自定义模板_8r5dkppcvq -->

            <!--            导入工厂选区域-->
            <a-modal v-model:visible="state.showAreaModal" title="请选择区域" @ok="handleAreaConfirm" :footer="null">
                <a-form ref="uploadRef" :model="state.uploadForm">
                    <a-row>
                        <a-col :span="24">
                            <a-form-item
                                label="所属区域"
                                :rules="[{ required: true, message: '请选择区域', trigger: 'blur' }]"
                                name="areaId"
                            >
                                <a-select
                                    allow-clear
                                    show-search
                                    v-model:value="state.uploadForm.areaId"
                                    :options="state.areaNameList"
                                    placeholder="请选择"
                                    :field-names="{ label: 'label', value: 'value' }"
                                    :filterOption="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                                    :max-tag-count="2"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item
                                :wrapper-col="{ span: 24 }"
                                name="attachmentList"
                                label="上传附件"
                                :rules="[{ required: true, message: '请上传附件', trigger: 'blur' }]"
                            >
                                <a-upload
                                    :disabled="!state.uploadForm.areaId"
                                    v-model:file-list="state.uploadForm.fileList"
                                    :multiple="true"
                                    :show-upload-list="false"
                                    :before-upload="handlerUploadProject"
                                    @remove="handlerRemoveProject"
                                    accept=".xlsx, image/*,.docx,, .xls,.mp4"
                                >
                                    <a-button type="primary">
                                        <upload-outlined />
                                        上传
                                    </a-button>
                                </a-upload>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </a-modal>
            <!--            导入工厂选区域-->
            <!--            数据分析-->
            <a-modal :visible="state.shareDataVisible" title="数据分析" @cancel="cancelShare" @ok="confirmShare">
                <a-form-item label="">
                    <a-tree-select
                        placeholder="请选择"
                        v-model:value="state.shareList"
                        show-search
                        style="width: 100%"
                        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                        allow-clear
                        multiple
                        treeDefaultExpandAll
                        :tree-data="userListData"
                        tree-node-filter-prop="label"
                        :maxTagCount="2"
                        :field-names="{
                            children: 'children',
                            label: 'label',
                            value: 'value'
                        }"
                    />
                </a-form-item>
            </a-modal>
            <!--            数据分析-->
            <div class="body">
                <div class="top-search">
                    <a-row :gutter="24">
                        <a-col :span="6">
                            <a-form-item label="所属区域" :labelCol="{ span: 5 }" :wrapperCol="{ span: 19 }">
                                <a-select
                                    allow-clear
                                    show-search
                                    v-model:value="state.searchForm.areaId"
                                    :options="state.areaNameList"
                                    placeholder="请选择"
                                    :field-names="{ label: 'label', value: 'value' }"
                                    :filterOption="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                                    @change="getData(false)"
                                    :max-tag-count="2"
                                    :getPopupContainer="getPopupContainer"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="企业名称" :labelCol="{ span: 5 }" :wrapperCol="{ span: 19 }">
                                <a-input
                                    placeholder="请输入关键字"
                                    v-model:value="state.searchForm.factoryName"
                                    @change="handleDebouncedSearch"
                                />
                            </a-form-item>
                        </a-col>

                        <a-col :span="6">
                            <a-form-item label="客户等级" :labelCol="{ span: 5 }" :wrapperCol="{ span: 19 }">
                                <a-select
                                    :options="state.khdjList"
                                    v-model:value="state.searchForm.customerLevel"
                                    placeholder="请选择"
                                    show-search
                                    allow-clear
                                    :filter-option="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                                    @change="getData(false)"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="企业性质" :labelCol="{ span: 5 }" :wrapperCol="{ span: 19 }">
                                <a-select
                                    :options="state.qyxzList"
                                    v-model:value="state.searchForm.basicEnterpriseNature"
                                    placeholder="请选择"
                                    allow-clear
                                    show-search
                                    :filter-option="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                                    @change="getData(false)"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="企业位置" :labelCol="{ span: 5 }" :wrapperCol="{ span: 19 }">
                                <a-tree-select
                                    v-model:value="state.searchForm.basicEnterpriseLocation"
                                    allowClear
                                    showSearch
                                    placeholder="请选择"
                                    tree-default-expand-all
                                    :tree-data="state.wzList"
                                    :field-names="{ label: 'title', value: 'title', key: 'value' }"
                                    tree-node-filter-prop="title"
                                    @change="getData(false)"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="2" offset="16" style="display: flex; justify-content: end; align-items: start">
                            <a-space>
                                <a-button @click="resetData" ghost type="primary"> 重置</a-button>
                            </a-space>
                        </a-col>
                    </a-row>
                </div>
                <div class="content">
                    <div class="table-top">
                        <div class="tip">客户列表</div>
                        <a-space>
                            <a-upload :multiple="true" :before-upload="handlerUploadArea" :show-upload-list="false">
                                <a-button
                                    type="primary"
                                    ghost
                                    class="import-btn radius4"
                                    v-permission="'3000001147_vid_sz5xgaij47'"
                                >
                                    <upload-outlined />导入区域</a-button
                                >
                            </a-upload>

                            <a-button
                                type="primary"
                                v-permission="'3000001147_vid_atozkpj0ee'"
                                ghost
                                class="import-btn radius4"
                                @click="showImportProject"
                            >
                                导入企业</a-button
                            >

                            <a-button
                                type="primary"
                                v-permission="'3000001147_vid_d2n7suqn9s'"
                                class="import-btn radius4"
                                @click="handleAddArea(null, 'add')"
                            >
                                新建区域客户</a-button
                            >
                            <a-button type="primary" @click="handleExpandAll" v-if="!state.isExpandAll"
                                >全部展开</a-button
                            >
                            <a-button type="primary" @click="handleCollapseAll" v-else>全部折叠</a-button>
                        </a-space>
                    </div>
                    <div class="scroll-content">
                        <a-spin :spinning="state.spinng" tip="加载中">
                            <div class="no-progress" v-if="state.dataSource.length == 0">
                                <div class="no-tip">
                                    <p class="message">暂无数据</p>
                                </div>
                            </div>
                            <div class="custom-item" v-for="(item, index) in state.dataSource">
                                <a-collapse
                                    :bordered="false"
                                    expandIconPosition="right"
                                    v-model:activeKey="state.collapseKey"
                                >
                                    <template #expandIcon="{ isActive }"> </template>
                                    <a-collapse-panel :key="item.id">
                                        <template #header>
                                            <div class="list-title">
                                                <div class="left">
                                                    <div @click.stop="toggleCollapse(item.id)" class="toggle-div">
                                                        <UpOutlined v-if="isActive(item.id)" class="active-icon" />
                                                        <DownOutlined v-else class="active-icon" />
                                                    </div>
                                                    <div class="area-img"></div>
                                                    <div class="area-name deep-font"> {{ item.areaName }}</div>
                                                </div>
                                                <div class="right">
                                                    <div>
                                                        <span class="light-font">创建时间：</span>
                                                        <span class="deep-font">{{ item.createdTime }}</span>
                                                    </div>
                                                    <div>
                                                        <span class="light-font">创建人：</span>
                                                        <span class="deep-font">{{ item.createdBy }}</span>
                                                    </div>
                                                    <div>
                                                        <span class="light-font">客成经理：</span>
                                                        <span class="deep-font">{{ item.customerManager }}</span>
                                                    </div>
                                                    <a-space>
                                                        <a-button
                                                            type="primary"
                                                            size="small"
                                                            class="title-btn radius2"
                                                            v-permission="'3000001147_vid_zcvmpg8pm6'"
                                                            @click.stop="handleAddFactory(null, item.id, 'add')"
                                                            >新建企业</a-button
                                                        >

                                                        <a-button
                                                            type="primary"
                                                            size="small"
                                                            class="title-btn radius2"
                                                            v-permission="'3000001147_vid_urvpl2pwtp'"
                                                            @click.stop="handleAddArea(item.id, 'detail')"
                                                            >详情</a-button
                                                        >
                                                        <a-popconfirm
                                                            placement="left"
                                                            title="确定删除吗?"
                                                            ok-text="确定"
                                                            cancel-text="取消"
                                                            @confirm="handleDeleteArea(item.id)"
                                                            @cancel="cancel"
                                                        >
                                                            <a-button
                                                                type="primary"
                                                                size="small"
                                                                v-permission="'3000001147_vid_x9vdj2vknl'"
                                                                class="title-btn radius2"
                                                                @click.stop=""
                                                                >删除</a-button
                                                            >
                                                        </a-popconfirm>

                                                        <!--                                                    <a-button-->
                                                        <!--                                                        type="primary"-->
                                                        <!--                                                        size="small"-->
                                                        <!--                                                        class="title-btn radius2"-->
                                                        <!--                                                        @click.stop="showShare(item.id)"-->
                                                        <!--                                                        >数据分享</a-button-->
                                                        <!--                                                    >-->
                                                    </a-space>
                                                </div>
                                            </div>
                                        </template>
                                        <div class="inner-content">
                                            <div class="inner-title deep-font mg12">年度政策：</div>
                                            <div class="mg12">
                                                <div class="inner-title light-font">方针基调：</div>
                                                <div class="content-font">
                                                    {{ item.yearPolicyPolicyTone }}
                                                </div></div
                                            >
                                            <div class="mg12">
                                                <div class="inner-title light-font">激励机制：</div>
                                                <div class="content-font">
                                                    {{ item.yearPolicyExcitationMechanism }}
                                                </div>
                                            </div>
                                            <div class="mg12">
                                                <div class="inner-title light-font">年度数智化建设预算：</div>
                                                <div class="content-font">
                                                    {{ item.yearPolicyDigitalConstructionBudget }}
                                                </div>
                                            </div>
                                            <div>
                                                <div class="inner-title light-font"
                                                    >判断政策导向对于信息化企业的态度和阻碍：</div
                                                >
                                                <div class="content-font">
                                                    {{ item.yearPolicyImpede }}
                                                </div>
                                            </div>
                                        </div>

                                        <div class="inner-table">
                                            <div class="inner-title deep-font mg12">所辖企业：</div>
                                            <a-table
                                                :columns="innerColumns"
                                                :data-source="item.factoryList"
                                                bordered
                                                :pagination="false"
                                            >
                                                <template #bodyCell="{ column, record, text }">
                                                    <template v-if="column.dataIndex === 'opration'">
                                                        <a-button
                                                            size="small"
                                                            type="link"
                                                            v-permission="'3000001147_vid_aa9314xhsm'"
                                                            @click="handleAddFactory(record.id, item.id, 'detail')"
                                                            >详情
                                                        </a-button>

                                                        <a-popconfirm
                                                            title="确定删除吗?"
                                                            ok-text="确定"
                                                            cancel-text="取消"
                                                            @confirm="handleDeleteFactory(record.id)"
                                                            @cancel="cancel"
                                                        >
                                                            <a-button
                                                                v-permission="'3000001147_vid_xx02r7owvc'"
                                                                size="small"
                                                                type="link"
                                                                >删除
                                                            </a-button>
                                                        </a-popconfirm>
                                                    </template>
                                                </template>
                                            </a-table>
                                        </div>
                                    </a-collapse-panel>
                                </a-collapse>
                            </div>
                        </a-spin>
                    </div>
                </div>
            </div>
            <!-- end vid_nmqzkbwwu1 自定义模板_8r5dkppcvq -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    onMounted(() => {
        getBaseUser()
        loadAllDictionaries()
        getData(true)
    })
    const state = reactive({
        inportFileList: [],
        dataSource: [],
        collapseKey: [],
        areaNameList: [],
        wzList: [],
        searchForm: {
            'areaId': undefined,
            'factoryName': undefined,
            'customerLevel': undefined,
            'basicEnterpriseNature': undefined,
            'basicEnterpriseLocation': undefined
        },
        shareDataVisible: false,
        showAreaModal: false,
        uploadForm: {
            fileList: [],
            areaId: undefined
        },
        isExpandAll: false,
        shareList: [],
        // 企业性质
        qyxzList: [],
        khdjList: [],
        qydjList: [],
        spinng: false
    })
    function getAreaName() {
        post('/solution-crm/api/v1/built-in-system-ppm/customer_area/customize_search', {})
            .then(data => {
                state.areaNameList = data.data.map(item => {
                    return {
                        label: item.areaName,
                        value: item.id
                    }
                })
            })
            .finally(() => {
                state.spinng = false
            })
    }
    import rawData from '@province-city-china/data'
    function getProvinceCityTree(data) {
        const provinces = data.filter(item => item.city === 0 || item.city === '00')
        const cities = data.filter(item => item.city !== 0 && item.city !== '00' && item.area === 0 && item.town === 0)

        const provinceMap = new Map()

        provinces.forEach(prov => {
            provinceMap.set(prov.province, {
                title: prov.name,
                value: prov.code,
                children: []
            })
        })

        cities.forEach(city => {
            const parent = provinceMap.get(city.province)
            if (parent) {
                parent.children.push({
                    title: city.name,
                    value: city.code
                })
            }
        })

        // 返回结构数组
        return Array.from(provinceMap.values())
    }

    state.wzList = getProvinceCityTree(rawData)
    const innerColumns = ref([
        {
            title: '企业全称',
            align: 'center',
            dataIndex: 'factoryName',
            ellipsis: true
        },
        {
            title: '企业简称',
            align: 'center',
            dataIndex: 'factoryShortName',
            ellipsis: true
        },
        {
            title: '所属区域',
            align: 'center',
            dataIndex: 'areaName',
            ellipsis: true
        },
        {
            title: '客户等级',
            align: 'center',
            dataIndex: 'customerLevel',
            ellipsis: true
        },
        {
            title: '企业性质',
            align: 'center',
            dataIndex: 'basicEnterpriseNature',
            ellipsis: true
        },
        {
            title: '企业位置',
            align: 'center',
            dataIndex: 'basicEnterpriseLocation',
            ellipsis: true
        },
        {
            title: '关联项目数',
            align: 'center',
            dataIndex: '',
            ellipsis: true
        },
        {
            title: '待回款金额',
            align: 'center',
            dataIndex: '',
            ellipsis: true
        },
        {
            title: '创建时间',
            align: 'center',
            dataIndex: 'createdTime',
            ellipsis: true
        },
        {
            title: '创建人',
            align: 'center',
            dataIndex: 'createdBy',
            ellipsis: true
        },
        {
            title: '客户经理',
            align: 'center',
            dataIndex: 'customerManager',
            ellipsis: true
        },
        {
            title: '操作',
            width: 150,
            align: 'center',
            dataIndex: 'opration'
        }
    ])
    function getData(flag) {
        state.spinng = true
        post('/solution-crm/api/v1/built-in-system-ppm/customer_area/customize_search', state.searchForm)
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    state.dataSource = []
                    return
                }
                state.dataSource = data.data
                if (flag) {
                    getAreaName()
                }
            })
            .finally(() => {
                state.spinng = false
            })
    }
    function resetData() {
        state.searchForm = {
            'areaId': undefined,
            'factoryName': undefined,
            'customerLevel': undefined,
            'basicEnterpriseNature': undefined,
            'basicEnterpriseLocation': undefined
        }
        getData(false)
    }
    //     展开折叠
    function toggleCollapse(id) {
        console.log('触发')
        const stringId = String(id) // 确保 id 为字符串格式
        if (isActive(stringId)) {
            // 如果当前面板是展开的，移除它的 ID
            state.collapseKey = state.collapseKey.filter(key => String(key) !== stringId)
        } else {
            // 否则，将它的 ID 添加到 collapseKey 中
            state.collapseKey.push(stringId)
        }
    }
    function isActive(id) {
        const stringId = String(id) // 确保 id 为字符串格式
        return state.collapseKey.includes(stringId) // 检查该 ID 是否在 collapseKey 中
    }
    state.dataSource.forEach(item => {
        state.collapseKey.push(item.id)
    })
    // function handleAddArea(id, type) {
    //     console.log(route.path)
    //     console.log(window.location, 'window.location.href')
    //     console.log(import.meta.env.VITE_PUBLIC_PATH, 'import.meta.env.VITE_PUBLIC_PATH')
    //     if (window.location.host.includes('localhost')) {
    //         console.log('本地环境')
    //         window.open(`${import.meta.env.VITE_PUBLIC_PATH}/page/3000001099?id=${id ? id : ''}&type=${type}`, '_blank')
    //     } else {
    //         const currentPath = location.pathname
    //         // 提取前缀路径（不包括最后的 page/xxxx）
    //         const basePath = currentPath.replace(/(page\/)\d+$/, '')
    //         console.log(basePath,'basePath');'/app_50000005/page/khgl'
    //         const newPageId = '3000001099'
    //         const newUrl = `${location.origin}${basePath}page/${newPageId}?id=${id ? id : ''}&type=${type}`
    //         window.open(`${newUrl}`, '_blank')
    //     }
    //     // window.open(`${import.meta.env.VITE_PUBLIC_PATH}/page/3000001099?id=${id ? id : ''}&type=${type}`, '_blank')
    // }
    function handleAddArea(id, type) {
        const isLocal = window.location.host.includes('localhost')
        const targetPageId = '3000001099'
        const query = new URLSearchParams({ id: id || '', type }).toString()

        if (isLocal) {
            console.log('本地环境')
            const url = `${import.meta.env.VITE_PUBLIC_PATH}/page/${targetPageId}?${query}`
            window.open(url, '_blank')
        } else {
            // 提取 pathname，确保最后是 page/数字
            console.log('线上')
            const match = location.pathname.match(/^(.*\/page\/)\d+$/)
            if (match) {
                const basePath = match[1] // e.g., "/app_50000005/allin-app/app_3000000076/page/"
                const url = `${location.origin}${basePath}${targetPageId}?${query}`
                window.open(url, '_blank')
            } else {
                console.error('当前 pathname 格式不符合预期，无法拼接新路径：', location.pathname)
            }
        }
    }

    // function handleAddFactory(factoryId, areaId, type) {
    //     window.open(
    //         `${import.meta.env.VITE_PUBLIC_PATH}/page/3000001100?factoryId=${
    //             factoryId ? factoryId : ''
    //         }&areaId=${areaId}&type=${type}`,
    //         '_blank'
    //     )
    // }
    function handleAddFactory(factoryId, areaId, type) {
        const isLocal = window.location.host.includes('localhost')
        const targetPageId = '3000001100'
        const query = new URLSearchParams({ factoryId: factoryId || '', areaId, type }).toString()
        if (isLocal) {
            console.log('本地环境')
            const url = `${import.meta.env.VITE_PUBLIC_PATH}/page/${targetPageId}?${query}`
            window.open(url, '_blank')
        } else {
            // 提取 pathname，确保最后是 page/数字
            console.log('线上')
            const match = location.pathname.match(/^(.*\/page\/)\d+$/)
            if (match) {
                const basePath = match[1] // e.g., "/app_50000005/allin-app/app_3000000076/page/"
                const url = `${location.origin}${basePath}${targetPageId}?${query}`
                window.open(url, '_blank')
            } else {
                console.error('当前 pathname 格式不符合预期，无法拼接新路径：', location.pathname)
            }
        }
    }
    // 上传文件区域
    function handlerUploadArea(file) {
        const data = new FormData()
        data.append('file', file)

        post('/solution-crm/api/v1/built-in-system-ppm/customer_area/import', data, {
            headers: { 'Content-Type': 'multipart/form-data' }
        })
            .then(res => {
                if (res?.code !== 200) {
                    message.error(res.message || '导入失败')
                } else {
                    message.success(res.message || '导入成功')
                    getData(true)
                }
            })
            .catch(err => {
                message.error('上传失败，请重试')
                console.error(err)
            })

        return false // 阻止默认上传行为
    }

    // 父移除文件
    function handlerRemoveProject(file) {
        state.uploadForm.fileList = state.uploadForm.fileList.filter(item => item.uid !== file.uid)
    }
    function handlerUploadProject(file) {
        const data = new FormData()
        data.append('file', file)

        post(`/solution-crm/api/v1/built-in-system-ppm/customer_area_factory/import/${state.uploadForm.areaId}`, data, {
            headers: { 'Content-Type': 'multipart/form-data' }
        })
            .then(res => {
                if (res?.code !== 200) {
                    message.error(res.message || '导入失败')
                } else {
                    message.success(res.message || '导入成功')
                    getData(true)
                    state.showAreaModal = false
                }
            })
            .catch(err => {
                message.error('上传失败，请重试')
                console.error(err)
            })

        return false
    }
    function showImportProject() {
        state.showAreaModal = true
    }
    const uploadRef = ref(null)
    function handleAreaConfirm() {
        uploadRef.value.validate().then(() => {
            post(
                `/solution-crm/api/v1/built-in-system-ppm/customer_area_factory/import/${state.uploadForm.areaId}`,
                state.uploadForm.fileList[0].originFileObj
            ).then(data => {
                if (data.code !== 200) {
                    message.error(data.message)

                    return
                }
                getData(true)
            })
        })
    }

    //     数据分析
    function showShare() {
        state.shareDataVisible = true
    }
    function confirmShare() {}
    function cancelShare() {
        state.shareDataVisible = false
    }
    const userListData = ref([])
    function getBaseUser() {
        get('/solution-crm/api/v1/built-in-system-ppm/customer_area/user_org').then(data => {
            const rawData = data.data
            markOrgNodesDisabled(rawData)
            console.log(rawData, 'adsdasdasdasdsad')
            userListData.value = convertUserTree(rawData)
        })
    }
    function markOrgNodesDisabled(nodes: any[]) {
        nodes.forEach(node => {
            if (node.type === 'ORG') {
                node.disabled = true
            }
            if (Array.isArray(node.children)) {
                markOrgNodesDisabled(node.children)
            }
        })
    }
    function fixTreeChildren(tree) {
        if (!Array.isArray(tree)) return []
        return tree.map(node => {
            const newNode = { ...node }
            if (newNode.children === null) {
                newNode.children = []
            } else if (Array.isArray(newNode.children)) {
                newNode.children = fixTreeChildren(newNode.children)
            }
            return newNode
        })
    }

    function convertUserTree(data) {
        return data.map(item => {
            const isUser = item.type === 'USER'
            const node: any = {
                label: item.name,
                value: isUser ? `${item.parentId}/${item.id}` : item.id, // 用户用 "组织ID/用户ID" 拼接
                disabled: item.disabled || false
            }

            if (!isUser && Array.isArray(item.children) && item.children.length > 0) {
                node.children = convertUserTree(item.children)
            }

            return node
        })
    }
    const selectedUserIds = computed(() => {
        return Array.from(new Set(state.searchForm.userList.map(v => v.split('/')[1])))
    })
    const dictMap = {
        'qyxzList': 'CUSTOMER.AREA.ENTERPRICE.NATURE',
        'qydjList': 'CUSTOMER.AREA.ENTERPRICE.LEVEL',
        'khdjList': 'CUSTOMER.AREA.KHDJ'
    }
    function loadAllDictionaries() {
        Object.entries(dictMap).forEach(([key, apiKey]) => {
            fetchDictionary(apiKey, key as keyof typeof state)
        })
    }
    function fetchDictionary(apiKey, target: keyof typeof state) {
        get(` /solution-ppm-basic-data/api/v1/dictionary/search/${apiKey}`).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            state[target] = data.data.map(item => ({
                label: item.itemName,
                value: item.itemName
            }))
        })
    }
    //     删除区域
    function handleDeleteArea(id) {
        del(`/solution-crm/api/v1/built-in-system-ppm/customer_area/customize_delete/${id}`).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            message.success(data.message)
            getData(true)
        })
    }
    //     删除工厂
    function handleDeleteFactory(id) {
        del(`/solution-crm/api/v1/built-in-system-ppm/customer_area_factory/customize_delete/${id}`).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            message.success(data.message)
            getData(false)
        })
    }
    //     全部展开
    function handleExpandAll() {
        state.isExpandAll = true
        state.dataSource.forEach(item => {
            state.collapseKey.push(item.id)
        })
    }
    //     全部折叠
    function handleCollapseAll() {
        state.isExpandAll = false
        state.collapseKey = []
    }
    const handleDebouncedSearch = debounce(getData, 500)
    function debounce(fn, delay = 300) {
        let timer = null
        return function (...args) {
            if (timer) clearTimeout(timer)
            timer = setTimeout(() => {
                fn.apply(this, args)
            }, delay)
        }
    }
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: hidden;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    /*
    样式*/
    /*折叠面板样式*/

    :deep(.ant3-collapse-header) {
        border-radius: 4px !important;
        border: none !important;
        color: #262626 !important;
        background: rgba(56, 117, 255, 0.1);
    }

    :deep(.ant3-collapse-borderless > .ant3-collapse-item > .ant3-collapse-content > .ant3-collapse-content-box) {
        padding: 0 12px 12px 12px !important;
        background: #eff4ff;
    }

    :deep(.ant3-collapse-icon-position-right > .ant3-collapse-item > .ant3-collapse-header) {
        padding: 16px;
        border-radius: 4px;
        color: #3875ff;
        background: #eff4ff;
        position: relative;
        border-radius: 4px 4px 0 0;
        border: 1px solid #eff4ff !important;
    }
    //:deep(.ant3-collapse-icon-position-right > .ant3-collapse-item > .ant3-collapse-header):hover {
    //    border: 1px solid #3875ff !important;
    //}

    //:deep(.ant3-collapse-item) {
    //    background: #ffffff;
    //}
    //:deep(
    //        .ant3-collapse .ant3-collapse-item-disabled > .ant3-collapse-header,
    //        .ant3-collapse .ant3-collapse-item-disabled
    //    ) {
    //    cursor: default;
    //}
    //:deep(.ant3-collapse-item) {
    //    background: #ffffff;
    //}

    .body {
        height: 100%;
    }
    .top-search {
        padding: 24px 24px 0 24px;
        border-radius: 4px;
        background-color: #fff;
        margin-bottom: 16px;
    }
    .content {
        padding: 24px;
        background-color: #fff;
        border-radius: 4px;
        height: 100%;
    }
    .table-top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 16px;
    }
    .tip {
        font-size: 16px;
        color: #262626;
        letter-spacing: 0;
        font-weight: 600;
        line-height: 16px;
        border-left: 4px solid #3875ff;
        padding-left: 4px;
        height: 16px;
    }
    .custom-item {
        margin-bottom: 16px;
        border-radius: 4px;
        border: 1px solid #eff4ff;
    }
    .custom-item:hover {
        border: 1px solid #3875ff !important;
    }
    .list-title {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 40px;
    }
    .left {
        width: 50%;
        display: flex;
        gap: 8px;
        align-items: center;
    }
    .right {
        display: flex;
        gap: 16px;
        align-items: center;
    }
    .toggle-div {
        display: flex;
        align-items: center;
    }
    .active-icon {
        color: #333333;
    }
    .area-img {
        width: 22px;
        height: 22px;
        flex-shrink: 0; /* 防止被压缩 */
        border-radius: 4px;
        background-size: cover;
        background-image: url('http://10.40.0.33:9001/file-storage/510370107191461888-source.png');
        border: 1px solid #d9d9d9;
    }
    /*字体样式*/
    .deep-font {
        color: #262626;
        font-weight: 600;
    }
    .light-font {
        font-size: 14px;
        color: #595959;
        letter-spacing: 0;
        font-weight: 400;
    }
    .area-name {
        display: block;
        max-width: 100%;
        font-size: 16px;
        color: #262626;
        letter-spacing: 0;
        font-weight: 600;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    //.title-btn {
    //    border: 1px solid rgba(56, 117, 255, 0.1);
    //    background: rgba(56, 117, 255, 0.1);
    //    color: #3875ff;
    //}
    //.title-btn:hover {
    //    border: 1px solid #3875ff;
    //}
    .inner-content {
        padding: 16px;
        border-radius: 4px;
        background-color: #fff;
    }
    .content-font {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        text-align: left;
        font-size: 14px;
        color: #262626;
        letter-spacing: 0;
        font-weight: 400;
    }
    .inner-table {
        padding: 16px;
        background-color: #fff;
        margin-top: 16px;
    }
    .scroll-content {
        height: calc(100% - 200px);
        overflow: auto;
        position: relative;
    }
    .no-progress {
        height: 370px;
        width: 100%;
        background-color: #fff;
        display: flex;
        justify-content: center;
        border: 1px solid #fff;
        border-radius: 10px;
        position: relative;
        /* 水平居中 */
    }
    .no-progress .no-tip {
        width: 200px;
        height: 101px;
        background-image: url('http://10.40.0.33:9001/file-storage/404789380744112128.png');
        background-size: cover;
        position: absolute;
        top: 30%;
        color: rgb(89, 89, 89);
    }
    .no-progress .no-tip .message {
        position: absolute;
        left: 35%;
        bottom: -40px;
        font-size: 16px;
        color: rgb(89, 89, 89);
    }
    .reset-btn {
        background-color: #d9d9d9;
        border-color: #d9d9d9;
        color: #262626;
    }
    .reset-btn:hover {
        background: #3875ff;
        border-color: #d9d9d9;
        color: #fff;
    }
    .import-btn:hover {
        background: #3875ff;
        border-color: #d9d9d9;
        color: #fff;
    }
    .radius4 {
        border-radius: 4px;
    }
    .radius2 {
        border-radius: 2px;
    }
    .mg4 {
        margin-bottom: 4px;
    }
    .mg12 {
        margin-bottom: 12px;
    }
    .inner-table:deep(.@{ant-prefix}-table-thead) > tr > th {
        background: #f2f2f2;
        color: #262626;
        font-weight: 600;
        padding: 10px 16px;
        border-right: 1px solid #d9d9d9 !important;
        position: relative;
    }
    .inner-table :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 400;
        color: #262626;
        border-bottom: 1px solid #d9d9d9;
        padding: 8px 16px;
        word-break: break-all;
    }
</style>
